/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.desktop.ui.dialog.card;

import kz.kstu.ent.business.entity.ResultSheet;
import kz.kstu.ent.business.entity.Student;
import kz.kstu.ent.desktop.chart.graph.StudentTotalGraph;
import kz.kstu.ent.desktop.chart.info.ChartInfo;
import kz.kstu.ent.desktop.common.DatasetConverter;
import kz.kstu.ent.desktop.components.model.AbstractNumeratedTableModel;
import kz.kstu.ent.desktop.images.GUIFactory;
import kz.kstu.ent.desktop.images.GUIIcon;
import kz.kstu.ent.desktop.util.GUIUtils;
import kz.kstu.ent.util.NumberUtil;
import kz.kstu.ent.util.StringUtil;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.TimeSeriesCollection;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * Date: 31.08.12
 * Time: 19:18
 *
 * @author Oleg Anastassov
 */
public class StudentCardDialog extends JDialog {

    private static final String TITLE = "Карточка студента";

    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    private JPanel rootPanel;
    private JTable resultSheetTable;
    private JButton closeButton;
    private JLabel labelFullName;
    private JLabel averageResultLabel;
    private JLabel maxResultLabel;
    private JButton graphButton;

    private ResultSheetTableModel tableModel;
    private Student student;

    public StudentCardDialog() {
        setIconImage(
                GUIFactory.getImage(GUIIcon.STUDENT)
        );
        tableModel = new ResultSheetTableModel();
    }

    public StudentCardDialog(Student student) {
        setIconImage(
                GUIFactory.getImage(GUIIcon.STUDENT)
        );
        tableModel = new ResultSheetTableModel();
        this.student = student;
    }

    public void initStaticComponents() {
        setContentPane(rootPanel);
        setModal(true);
        setSize(WIDTH, HEIGHT);
        resultSheetTable.setModel(new ResultSheetTableModel());
        setResizable(false);
        resultSheetTable.getTableHeader().setReorderingAllowed(false);
        resultSheetTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        TableColumnModel columnModel = resultSheetTable.getColumnModel();
        TableColumn idColumn = columnModel.getColumn(AbstractNumeratedTableModel.ID_COLUMN_INDEX);
        idColumn.setMinWidth(0);
        idColumn.setMaxWidth(0);
        setTitle(TITLE);

        resultSheetTable.setComponentPopupMenu(createPopupMenu());

        initIcons();
        initListeners();
    }

    public void initData() {
        if (student != null) {
            List<ResultSheet> sheets = student.getResultSheetList();
            tableModel.setData(sheets);
            resultSheetTable.setModel(tableModel);

            labelFullName.setText(
                    StringUtil.concatenate(
                            student.getSurname(),
                            student.getName(),
                            student.getPatronymic()
                    )
            );
            if (student.getAltynBelgi()) {
                labelFullName.setIcon(
                        GUIFactory.getIcon(GUIIcon.MEDAL)
                );
            }

            ResultSheetHelper helper = new ResultSheetHelper();
            Integer sumAll = 0;
            Integer max = 0;
            for (ResultSheet rs : sheets) {
                int sum = helper.getSumAll(rs);
                sumAll += sum;

                if (sum > max) {
                    max = sum;
                }
            }
            Double averageResult = (double) sumAll / sheets.size();
            averageResultLabel.setText(NumberUtil.formatDouble(averageResult));
            maxResultLabel.setText(max.toString());
        }

//        ResultSheetDelegate delegate = new ResultSheetDelegateImpl();
//        List<ResultSheet> sheets = delegate.findAll(ResultSheet.class);
//        tableModel.setData(sheets);
//        resultSheetTable.setModel(tableModel);

//        // center values
//        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
//        centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
//        for (int i = 0; i < resultSheetTable.getColumnCount(); i++) {
//            // columns
//            resultSheetTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);
////            resultSheetTable.getColumnModel().getColumn(i).setHeaderRenderer(centerRenderer);
//        }

    }

    private void initListeners() {
        graphButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DatasetConverter converter = new DatasetConverter();
                final TimeSeriesCollection dataset = converter.convertResultSheets(student.getResultSheetList());
                StudentTotalGraph graph = new StudentTotalGraph(
                        new ChartInfo(
                                "Общее количество баллов : "
                                        + StringUtil.concatenate(
                                        student.getSurname(),
                                        student.getName(),
                                        student.getPatronymic()
                                ),
                                "Очередная сдача пробного ЕНТ",
                                "К-во баллов"
                        ),
                        dataset
                );
                JFreeChart chart = graph.build();

                // вынести в общий механизм
                String title = graph.getChartInfo().getTitle();
                ChartFrame chartFrame = new ChartFrame(title, chart);
                chartFrame.setIconImage(GUIFactory.getImage(GUIIcon.GRAPH));
                chartFrame.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
                chartFrame.setMinimumSize(new Dimension(600, 400));
                chartFrame.setExtendedState(chartFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
                GUIUtils.centerAndShow(chartFrame);
            }
        });
    }

    private void initIcons() {
        graphButton.setIcon(
                GUIFactory.getIcon(GUIIcon.GRAPH)
        );
        closeButton.setIcon(
                GUIFactory.getIcon(GUIIcon.CANCEL)
        );
    }

    private JPopupMenu createPopupMenu() {
        JPopupMenu pm = new JPopupMenu();

        JMenuItem miEdit = new JMenuItem(
                "Редактировать...",
                GUIFactory.getIcon(GUIIcon.EDIT)
        );
        JMenuItem miAdd = new JMenuItem(
                "Добавить...",
                GUIFactory.getIcon(GUIIcon.ADD)
        );
        JMenuItem miDelete = new JMenuItem(
                "Удалить...",
                GUIFactory.getIcon(GUIIcon.DELETE)
        );
        pm.add(miEdit);
        pm.addSeparator();
        pm.add(miAdd);
        pm.add(miDelete);
        return pm;
    }

    private static class HeaderRenderer implements TableCellRenderer {

        DefaultTableCellRenderer renderer;

        public HeaderRenderer(JTable table) {
            renderer = (DefaultTableCellRenderer)
                    table.getTableHeader().getDefaultRenderer();
            renderer.setHorizontalAlignment(JLabel.CENTER);
        }

        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int col) {
            return renderer.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, col);
        }
    }


}
